#!/usr/bin/env node

/**
 * 发布脚本
 * 用于自动化发布到npm
 */

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 颜色输出
const colors = {
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  reset: '\x1b[0m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function execCommand(command, description) {
  log(`\n${description}...`, 'blue');
  try {
    execSync(command, { stdio: 'inherit' });
    log(`✓ ${description} 完成`, 'green');
  } catch (error) {
    log(`✗ ${description} 失败: ${error.message}`, 'red');
    process.exit(1);
  }
}

function checkGitStatus() {
  log('检查Git状态...', 'blue');
  try {
    const status = execSync('git status --porcelain', { encoding: 'utf8' });
    if (status.trim()) {
      log('发现未提交的更改，请先提交所有更改', 'yellow');
      process.exit(1);
    }
    log('✓ Git状态检查通过', 'green');
  } catch (error) {
    log('✗ Git状态检查失败', 'red');
    process.exit(1);
  }
}

function checkPackageJson() {
  log('检查package.json...', 'blue');
  const packagePath = path.join(process.cwd(), 'package.json');
  if (!fs.existsSync(packagePath)) {
    log('✗ 未找到package.json文件', 'red');
    process.exit(1);
  }
  
  const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
  if (!packageJson.name || !packageJson.version) {
    log('✗ package.json缺少必要字段', 'red');
    process.exit(1);
  }
  
  log(`✓ 包名: ${packageJson.name}`, 'green');
  log(`✓ 版本: ${packageJson.version}`, 'green');
}

function main() {
  log('开始发布流程...', 'blue');
  
  // 检查Git状态
  checkGitStatus();
  
  // 检查package.json
  checkPackageJson();
  
  // 运行测试
  execCommand('npm test', '运行测试');
  
  // 运行代码检查
  execCommand('npm run lint', '运行代码检查');
  
  // 构建项目
  execCommand('npm run build', '构建项目');
  
  // 检查构建产物
  const distPath = path.join(process.cwd(), 'dist');
  if (!fs.existsSync(distPath)) {
    log('✗ 构建产物不存在', 'red');
    process.exit(1);
  }
  
  // 发布到npm
  execCommand('npm publish', '发布到npm');
  
  log('\n🎉 发布成功！', 'green');
  log('包已成功发布到npm，您可以在 https://www.npmjs.com/package/chic-core 查看', 'blue');
}

// 处理命令行参数
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
  log('发布脚本使用说明:', 'blue');
  log('  node scripts/publish.js          # 执行完整发布流程', 'green');
  log('  node scripts/publish.js --help   # 显示帮助信息', 'green');
  process.exit(0);
}

main();
